package test2.guava;

import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;

import org.junit.Test;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;

public class CacheTest {
	
	Cache<String, String> cache = CacheBuilder
			.newBuilder()
			.maximumSize(2)
			.recordStats()
			.build();
	
	List<String> names = Arrays.asList(new String[]{"zhangsan", "lisi", "xiaoming", "fazheng", "zhuge", "fenghuang"});
	
	@Test
	public void test1() {
		for(int i=0;i<10;i++) {
			System.out.println(getUserById(new Random().nextInt(5)));
		}
		System.out.println(cache.stats());
	}
	
	public String getUserById(int id) {
		try {
			System.out.println("加载中...[" + id + "]");
			return cache.get("user:" + id, new Callable<String>() {
				@Override
				public String call() throws Exception {
					System.out.println("[" + id + "]未命中");
					return names.get(id);
				}
			});
		} catch (ExecutionException e) {
			e.printStackTrace();
			return null;
		}
	}

}
